﻿using ConsoleApp.TestFunc.Interface;
using ConsoleApp.TestFunc.Service;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp.TestFunc.测试代码
{
    /// <summary>
    /// 自定义依赖注入容器
    /// </summary>
    public class Example_CustomDIContainer
    {
        public class SimpleDIContainer
        {
            private readonly Dictionary<Type, Type> _serviceMap = new Dictionary<Type, Type>();

            public void RegisterService<TService, TImplementation>()
                where TImplementation : TService
            {
                _serviceMap[typeof(TService)] = typeof(TImplementation);
            }

            //解析服务
            public TService ResolveService<TService>()
            {
                return (TService)ResolveService(typeof(TService));
            }

            // 新增：根据 Type 解析（支持递归）
            private object ResolveService(Type serviceType)
            {
                if (!_serviceMap.TryGetValue(serviceType, out var implementationType))
                {
                    throw new InvalidOperationException($"No service registered for {serviceType.Name}");
                }

                return CreateInstance(implementationType);
            }

            //创建实例
            private object CreateInstance(Type implementationType)
            {
                var constructors = implementationType.GetConstructors();
                if (constructors.Length == 0)
                {
                    throw new InvalidOperationException($"No public constructor found for type {implementationType.Name}");
                }

                //从一个类的所有公共构造函数中，选择“参数最多”的那个构造函数。
                var constructor = constructors.OrderByDescending(c => c.GetParameters().Length).First();
                var parameters = constructor.GetParameters();

                //声明数组
                var parameterInstances = new object[parameters.Length];

                for (int i = 0; i < parameters.Length; i++)
                {
                    parameterInstances[i] = ResolveService(parameters[i].ParameterType);
                }

                return constructor.Invoke(parameterInstances);
            }
        }


        //测试方法
        public static void Run()
        {
            //使用依赖注入容器
            var container = new SimpleDIContainer();

            container.RegisterService<IEmailService, SmtpEmailService>();
            container.RegisterService<CustomerService, CustomerService>();
            var customerService = container.ResolveService<CustomerService>();
            customerService.RegisterCustomer("user@example.com");
        }

        //测试方法
        public void Test()
        {
            Console.WriteLine("测试");
        }
    }

}
